<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import DialogForm from '@/components/DialogForm.vue'
import { listOrder, getOrder, updateOrder, delOrder } from '@/api/order'
import { listUser } from '@/api/user'
import { listMedicine } from '@/api/medicine'

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  if (isNaN(date.getTime())) return dateTime;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 表格数据
const tableData = ref([])
// 加载状态
const loading = ref(false)
// 用户列表
const userList = ref([])
// 药品列表
const medicineList = ref([])
// 订单明细
const orderItems = ref([])
// 表格列配置
const columns = [
  { 
    prop: 'userId', 
    label: '用户名', 
    width: '120',
    formatter: (val) => {
      const user = userList.value.find(item => item.id === val)
      return user ? user.userName : ''
    }
  },
  { 
    prop: 'orderStatus', 
    label: '订单状态', 
    width: '120',
    formatter: (val) => {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成'
      }
      return statusMap[val] || '未知状态'
    }
  },
  { 
    prop: 'totalAmount', 
    label: '总金额', 
    width: '120',
    formatter: (val) => `¥${(val / 100).toFixed(2)}`
  },
  { prop: 'createTime', label: '下单时间', width: '180', formatter: (val) => formatDateTime(val) }
]
// 搜索字段
const searchFields = ['userId', 'orderStatus']

// 表单数据
const formData = reactive({
  id: null,
  userId: null,
  orderStatus: 0,
  totalAmount: 0,
  createTime: ''
})

// 表单字段配置 - 编辑模式
const editFormFields = ref([
  { 
    prop: 'userId', 
    label: '用户', 
    type: 'select', 
    required: true,
    options: []
  },
  { 
    prop: 'orderStatus', 
    label: '订单状态', 
    type: 'select', 
    required: true,
    options: [
      { label: '待支付', value: 0 },
      { label: '已支付', value: 1 },
      { label: '已发货', value: 2 },
      { label: '已完成', value: 3 }
    ]
  },
  { 
    prop: 'totalAmount', 
    label: '总金额(元)', 
    type: 'number', 
    required: true,
    disabled: true,
    min: 0,
    precision: 2
  },
  { prop: 'createTime', label: '下单时间', type: 'input', disabled: true }
])

// 表单字段配置 - 查看模式
const viewFormFields = ref([
  { 
    prop: 'userId', 
    label: '用户', 
    type: 'select', 
    disabled: true,
    options: []
  },
  { 
    prop: 'orderStatus', 
    label: '订单状态', 
    type: 'select', 
    disabled: true,
    options: [
      { label: '待支付', value: 0 },
      { label: '已支付', value: 1 },
      { label: '已发货', value: 2 },
      { label: '已完成', value: 3 }
    ]
  },
  { 
    prop: 'totalAmount', 
    label: '总金额(元)', 
    type: 'number', 
    disabled: true,
    min: 0,
    precision: 2
  },
  { prop: 'createTime', label: '下单时间', type: 'input', readonly: true }
])

// 表单规则
const formRules = {
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  orderStatus: [
    { required: true, message: '请选择订单状态', trigger: 'change' }
  ]
}

// 对话框配置
const dialogConfig = reactive({
  visible: false,
  title: '查看订单',
  isEdit: false,
  isView: false
})

// 订单明细对话框配置
const itemsDialogConfig = reactive({
  visible: false,
  title: '订单明细',
  orderId: null,
  loading: false
})

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    tableData.value = await listOrder()
  } catch (error) {
    console.error('获取订单列表失败', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    userList.value = await listUser()
    // 更新表单字段配置中的用户选项
    const userOptions = userList.value.map(item => ({
      label: item.userName,
      value: item.id
    }))
    
    // 更新用户选项
    editFormFields.value.find(item => item.prop === 'userId').options = userOptions
    viewFormFields.value.find(item => item.prop === 'userId').options = userOptions
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取药品列表
const getMedicineList = async () => {
  try {
    medicineList.value = await listMedicine()
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  }
}

// 编辑订单
const handleEdit = async (row) => {
  try {
    const res = await getOrder(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        if (key === 'totalAmount' && res[key] !== undefined) {
          // 将分转换为元
          formData[key] = res[key] / 100
        } else {
          formData[key] = res[key] || ''
        }
      })
      
      dialogConfig.title = '编辑订单'
      dialogConfig.isEdit = true
      dialogConfig.isView = false
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取订单详情失败', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 查看订单
const handleView = async (row) => {
  try {
    const res = await getOrder(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        if (key === 'totalAmount' && res[key] !== undefined) {
          // 将分转换为元
          formData[key] = res[key] / 100
        } else {
          formData[key] = res[key] || ''
        }
      })
      
      dialogConfig.title = '查看订单'
      dialogConfig.isEdit = false
      dialogConfig.isView = true
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取订单详情失败', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 删除订单
const handleDelete = async (row) => {
  try {
    ElMessageBox.confirm('确定要删除该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await delOrder(row.id)
      ElMessage.success('删除成功')
      getOrderList()
    }).catch(() => {})
  } catch (error) {
    console.error('删除订单失败', error)
    ElMessage.error('删除订单失败')
  }
}

// 批量删除订单
const handleBatchDelete = async (rows) => {
  try {
    ElMessageBox.confirm(`确定要删除选中的 ${rows.length} 个订单吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await Promise.all(rows.map(row => delOrder(row.id)))
      ElMessage.success('批量删除成功')
      getOrderList()
    }).catch(() => {})
  } catch (error) {
    console.error('批量删除订单失败', error)
    ElMessage.error('批量删除订单失败')
  }
}

// 提交表单
const handleSubmit = async (data) => {
  try {
    // 处理价格，将元转换为分
    const submitData = { ...data }
    submitData.totalAmount = Math.round(submitData.totalAmount * 100)
    
    // 编辑
    await updateOrder(submitData)
    ElMessage.success('编辑成功')
    
    // 刷新列表
    getOrderList()
    // 关闭对话框
    dialogConfig.visible = false
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}

// 切换到编辑模式
const switchToEdit = () => {
  dialogConfig.title = '编辑订单'
  dialogConfig.isEdit = true
  dialogConfig.isView = false
}

// 生成模拟订单明细数据
const generateMockOrderItems = (orderId) => {
  // 根据订单ID生成一些模拟数据
  const mockItems = []
  
  // 随机生成2-5个订单项
  const itemCount = Math.floor(Math.random() * 4) + 2
  
  for (let i = 0; i < itemCount; i++) {
    // 如果有药品列表，从中随机选择一个
    let medicineId = i + 1
    if (medicineList.value.length > 0) {
      const randomIndex = Math.floor(Math.random() * medicineList.value.length)
      medicineId = medicineList.value[randomIndex].id
    }
    
    // 随机数量和价格
    const quantity = Math.floor(Math.random() * 5) + 1
    const price = Math.floor(Math.random() * 10000) + 500 // 5-105元之间的随机价格，单位分
    
    mockItems.push({
      id: i + 1,
      orderId,
      medicineId,
      quantity,
      price
    })
  }
  
  return mockItems
}

// 查看订单明细
const handleViewItems = async (row) => {
  try {
    itemsDialogConfig.orderId = row.id
    itemsDialogConfig.loading = true
    itemsDialogConfig.visible = true
    
    // 使用模拟数据代替API调用
    setTimeout(() => {
      orderItems.value = generateMockOrderItems(row.id)
      itemsDialogConfig.loading = false
    }, 500) // 模拟网络延迟
  } catch (error) {
    console.error('获取订单明细失败', error)
    ElMessage.error('获取订单明细失败')
    orderItems.value = []
    itemsDialogConfig.loading = false
  }
}

// 初始化
onMounted(async () => {
  await Promise.all([getUserList(), getMedicineList()])
  getOrderList()
})
</script>

<template>
  <div class="order-container">
    <el-card shadow="never" class="order-card">
      <template #header>
        <div class="card-header">
          <h3>订单管理</h3>
        </div>
      </template>
      
      <!-- 表格 -->
      <data-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :search-fields="searchFields"
        @edit="handleEdit"
        @view="handleView"
        @delete="handleDelete"
        @batch-delete="handleBatchDelete"
        @refresh="getOrderList"
      >
        <template #operation="{ row }">
          <el-button type="primary" size="small" @click="handleViewItems(row)">
            查看明细
          </el-button>
        </template>
      </data-table>
    </el-card>
    
    <!-- 表单对话框 - 编辑 -->
    <dialog-form
      v-if="!dialogConfig.isView"
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="editFormFields"
      :rules="formRules"
      @submit="handleSubmit"
    >
      <template #createTime="{ value }">
        {{ formatDateTime(value) }}
      </template>
    </dialog-form>
    
    <!-- 表单对话框 - 查看 -->
    <dialog-form
      v-else
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="viewFormFields"
      :readonly="true"
      :show-confirm-button="false"
      :cancel-button-text="'关闭'"
    >
      <template #createTime="{ value }">
        {{ formatDateTime(value) }}
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogConfig.visible = false">关闭</el-button>
          <el-button type="primary" @click="switchToEdit">编辑</el-button>
        </div>
      </template>
    </dialog-form>
    
    <!-- 订单明细对话框 -->
    <el-dialog v-model="itemsDialogConfig.visible" :title="itemsDialogConfig.title" width="700px">
      <div v-loading="itemsDialogConfig.loading">
        <el-empty v-if="!orderItems.length && !itemsDialogConfig.loading" description="暂无订单明细" />
        <el-table v-else :data="orderItems" border style="width: 100%">
          <el-table-column label="药品名称" prop="medicineName" min-width="180">
            <template #default="{ row }">
              {{ medicineList.find(item => item.id === row.medicineId)?.medicineName || '药品' + row.medicineId }}
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="100" />
          <el-table-column label="单价" prop="price" width="120">
            <template #default="{ row }">
              ¥{{ (row.price / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              ¥{{ ((row.price * row.quantity) / 100).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        
        <div v-if="orderItems.length" class="order-total">
          <span>总计：</span>
          <span class="price">
            ¥{{ (orderItems.reduce((sum, item) => sum + (item.price * item.quantity), 0) / 100).toFixed(2) }}
          </span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="itemsDialogConfig.visible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-container {
  height: 100%;
}

.order-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  flex: 1;
  overflow: auto;
  padding: 15px;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

.order-total {
  margin-top: 15px;
  text-align: right;
  padding-right: 20px;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
  margin-left: 8px;
}
</style> 